package com.tool.genxml;

import com.tool.genxml.handler.ComponentHandler;
import com.tool.genxml.handler.ComponentSheetHandler;
import com.tool.genxml.handler.MsgSheetHandler;
import com.tool.common.utils.SystemUtil;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

import static com.tool.genxml.constant.SysConstant.COMPONENT_CHINESE;

public class GenMain {

    public static void main(String[] args) throws IOException {

        // 输入的Excel文件名
        String fileName = args[0];

        // 是否需要生成xml
        boolean createXml = Integer.parseInt(args[1]) == 1;
        // 是否需要生成配置文件
        boolean createConfig = Integer.parseInt(args[2]) == 1;

        String outName = "outConfig.xlsx";
        if (createConfig && args.length == 4) {
            // 如果不需要生成配置文件，则不需要该参数，输出的Excel文件名
            outName = args[3];
        }

        // 加载当前目录
        String projectPath = SystemUtil.loadProjectPath();

        File file = new File(projectPath, fileName);
        // 读取Excel
        FileInputStream fis = new FileInputStream(file);
        XSSFWorkbook workbook = new XSSFWorkbook(fis);

        XSSFSheet compSheet = workbook.getSheet(COMPONENT_CHINESE);
        // 解析组件
        ComponentHandler compHandler = new ComponentSheetHandler(compSheet);
        compHandler.exec();

        int tabs = workbook.getNumberOfSheets();

        // 生成输出的Excel
        XSSFWorkbook outWorkBook = new XSSFWorkbook();

        // 循环
        for (int i = 0; i < tabs; i++) {

            // 解析其他非组件sheet页
            XSSFSheet sheet = workbook.getSheetAt(i);

            // 排除sheet页名为组件的sheet页
            if (Objects.equals(COMPONENT_CHINESE, sheet.getSheetName())) {
                continue;
            }

            // 解析sheet页
            MsgSheetHandler msgSheetHandler = new MsgSheetHandler(sheet, compHandler);
            msgSheetHandler.exec();

            // 生成xml
            XmlGen xmlGen = new XmlGen(msgSheetHandler);
            xmlGen.parse();

            if (createXml) {
                xmlGen.createXmlFile(projectPath + "/" + sheet.getSheetName() + ".xml");
            }

            if (createConfig) {
                xmlGen.addSheet(outWorkBook);
            }
        }

        if (createConfig) {
            // 判断是否要在Excel表中添加xml路径
            outWorkBook.write(new FileOutputStream(new File(projectPath, outName)));
        }
    }

}
